-- Radical by Basil Voronkov
-- Module 'table'
---------------------------------------------
-- Table extension functions

function table.len(self)
  local count = 0;
  for i,v in pairs(self) do 
    count = count + 1;
  end
  return count;
end

function table.tostring(tbl)
  local res, done = {}, {};
  for k,v in ipairs(tbl) do
    table.insert(res, table.value_tostring(v));
    done[k] = true;
  end
  for k,v in pairs(tbl) do
    if not done[k] then
      table.insert(res, table.key_tostring(k).."="..table.value_tostring(v));
    end
  end
  return "("..table.concat(res, ",")..")";
end

function table.append(tab, val)
  if tab == nil then
    tab = {};
  end
  table.insert(tab, val);
  return tab;
end

function table.value_tostring(v)
  if is_string(v) then
    local vs = v:gsub("\n", "\\n");
    if string.match(vs:gsub("[^'\"]",""), '^"+$') then
      return "'"..vs.."'";
    end
    return '"'..vs:gsub('"', '\\"')..'"';
  elseif is_table(v) then
    return table.tostring(v);
  else
    return tostring(v);
  end
end

function table.key_tostring(k)
  if is_string(k) and string.match(k, "^[_%a][_%a%d]*$") then
    return k;
  else
    return "["..table.value_tostring(k).."]";
  end
end
